package com.lanyou.esb.web.serviceLogManagement;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.xml.sax.SAXException;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.lanyou.cook.common.Constants;
import com.lanyou.cook.entity.domain.ParamSetting;
import com.lanyou.cook.paramsetting.ParamSettingReppository;
import com.lanyou.cook.util.gson.GsonUtil;
import com.lanyou.esb.exception.BundleActionException;
import com.lanyou.esb.service.SystemLogLevelManagementService;
import com.lanyou.esb.servicemix.bean.Log;
import com.lanyou.esb.vo.ComboxEntryVo;
import com.lanyou.esb.web.param.SystemLogLevelManagementParam;

/**
 * ServiceMix服务日志控制器
 * 
 * @author Davey.wu
 */
@RestController
@RequestMapping(Constants.BASE_URL_API + "/systemLogLevelManagement")
public class SystemLogLevelManagementController {
	@Autowired
	SystemLogLevelManagementService systemLogLevelManagementService;

	@Autowired
	private ResourceLoader resourceLoader;

	@Autowired
	private ParamSettingReppository paramSettingReppository;

	/**
	 * 查找ServiceMix服务日志，分页
	 * 
	 * @param param
	 *            :查询条件
	 * @param pageable
	 *            ：分页对象
	 * @return
	 * @throws BundleActionException
	 */
	@RequestMapping("/findSystemLogLevelInfos")
	public Page<Log> findSystemLogLevelInfos(
			SystemLogLevelManagementParam param, Pageable pageable)
			throws BundleActionException {

		return systemLogLevelManagementService.findSystemLogLevelInfos(param,
				pageable);
	}

	/**
	 * 获取ESB节点信息
	 * 
	 * @param param
	 * @param pageable
	 * @return
	 * @throws BundleActionException
	 */
	@RequestMapping("/getEsbNodes")
	public String getEsbNodes() throws BundleActionException {
		List<ComboxEntryVo> result = new ArrayList<>();
		// 查找ServiceMix服务节点信息
		ParamSetting paramSettingServer = paramSettingReppository
				.findByParamName(Constants.SERVERMIX_SERVER);
		// 没有记录，返回空值
		if (paramSettingServer == null) {
			return GsonUtil.getDefaultGson().toJson(result);
		}
		try {
			JsonArray jsonDatas = GsonUtil.getDefaultJsonParser()
					.parse(paramSettingServer.getParamValue()).getAsJsonArray();
			// 解析节点信息
			for (JsonElement jsonElement : jsonDatas) {
				String ip = jsonElement.getAsJsonObject().get("ip")
						.getAsString();
				ComboxEntryVo vo = new ComboxEntryVo();
				vo.setValueCode(ip);
				vo.setValueName(ip);
				result.add(vo);
			}
		} catch (Exception e) {
		}
		return GsonUtil.getDefaultGson().toJson(result);
	}

	/**
	 * 导出ServiceMix服务日志
	 * 
	 * @param service
	 *            ：服务名称
	 * @param bundleName
	 *            ：BUNDLE名称
	 * @param level
	 *            ：日志级别
	 * @param startReceivedTime
	 *            ：开始时间
	 * @param endReceivedTime
	 *            ：结束时间
	 * @param request
	 *            :HTTP 请求对象
	 * @param response
	 *            ：HTTP 响应对象
	 * @throws IOException
	 * @throws InvalidFormatException
	 * @throws SAXException
	 * @throws ParseException
	 * @throws BundleActionException
	 */
	@ResponseBody
	@RequestMapping(value = "/systemLogLevelExport", produces = "application/json")
	public void systemLogLevelExport(String serviceMixIp, String service,
			String bundleName, String level, HttpServletRequest request,
			HttpServletResponse response) throws IOException,
			InvalidFormatException, SAXException, ParseException,
			BundleActionException {
		// 组装查询条件
		SystemLogLevelManagementParam param = new SystemLogLevelManagementParam();
		param.setServiceMixIp(serviceMixIp);
		param.setService(service);
		param.setBundleName(bundleName);
		param.setLevel(level);
		// 获取数据
		List<Log> logs = systemLogLevelManagementService
				.findSystemLogLevelInfos(param);
		// 文件名
		String fileName = new String(
				Constants.SYSTEM_LOG_LEVEL_REPORT.getBytes("gb2312"),
				"ISO8859-1");
		// 获取导出模板
		InputStream in = resourceLoader.getResource(
				"classpath:jxls/templatestIn/systemLogLevelManagement.xls")
				.getInputStream();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition", "attachment;filename="
				+ fileName + ".xls");
		OutputStream os = response.getOutputStream();
		Context context = new Context();
		context.putVar("logs", logs);
		JxlsHelper.getInstance().processTemplate(in, os, context);
	}

}
